package com.dayuan.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dayuan.bean.BackMenu;
import com.dayuan.bean.BackRole;
import com.dayuan.bean.BackUser;
import com.dayuan.dao.AdminUserMapper;

@Service
public class AdminUserService {

	@Resource
	private AdminUserMapper adminUserMapper;

	/* 注册帐号 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void insertUser(BackUser au) {
		try {
			adminUserMapper.insertAdminUser(au);
			adminUserMapper.insertAdminUserAndRole(au.getId());
		} catch (Exception e) {
			throw e;
		}

	}

	/* 验证帐号密码 */
	public BackUser selectAdminUser(BackUser au) {
		return adminUserMapper.selectAdminUser(au);
	}

	/* 查询rid */
	public List<Integer> selectUserRole(int uid) {
		return adminUserMapper.selectUserRole(uid);
	}

	/* 查询权限 */
	public List<BackRole> selectPermission(int uid) {
		List<Integer> rid = adminUserMapper.selectUserRole(uid);
		List<BackRole> adminRole = new ArrayList<>();

		for (Integer integer : rid) {
			BackRole role = adminUserMapper.selectRoleByRid(integer);
			adminRole.add(role);
		}
		return adminRole;
	}

	/*
	 * ———————————————————————————————商家审核start—————————————————————————————————
	 * ————————
	 */

	/* 查询总行数 */
	public int selectAdminUserTotal() {
		return adminUserMapper.selectAdminUserTotal();
	}

	/* 分页查看 */
	public List<BackUser> selectAdminUserLimit(int startIndex, int number) {
		return adminUserMapper.selectAdminUserLimit(startIndex, number);
	}

	/* 审核通过 */
	public void updateUserPass(int id) {
		adminUserMapper.updateUserPass(id);
	}

	/* 审核不通过 */
	public void updateUserNotPass(int id) {
		adminUserMapper.updateUserNotPass(id);
	}

	/*
	 * ———————————————————————————————商家审核end———————————————————————————————————
	 * ——————
	 */

	/**
	 * 获取角色菜单
	 * 
	 * @param uid
	 * @return
	 */
	public List<BackMenu> getMenu(int uid) {
		// 菜单集合
		List<BackMenu> adminMenus = new ArrayList<>();
		// 菜单id集合
		List<Integer> mList = new ArrayList<>();
		List<Integer> rids = adminUserMapper.selectUserRole(uid);
		for (Integer rid : rids) {
			List<Integer> mids = adminUserMapper.selectRoleMenu(rid);
			for (Integer mid : mids) {
				if (!mList.contains(mid)) {
					mList.add(mid);
					BackMenu adminMenu = adminUserMapper.selectMenu(mid);
					adminMenus.add(adminMenu);
				}
			}

		}
		return adminMenus;
	}

	/*增加头像地址*/
	public void updateUserPicture(String picture, int id) {
		adminUserMapper.updateUserPicture(picture, id);
	}

}
